<template>
  <div class="ele-body">
    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="upgradeId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          v-model:selection="selection"
          :scroll="{ x: 'max-content' }"
        >
          <!-- table上边工具栏 -->
          <template #toolbar>
            <a-space>
              <a-button v-permission="['PROPERTY_DEVICELIST_MGR_SLURRY_SOFTWARE_Upgrade_BUTTON']" style='border: none;' type="primary" @click="openEdit()">
                <template #icon>
                  <plus-outlined />
                </template>
                <span>新建升级</span>
              </a-button>

              <a-button style='border: none;' type="primary" @click="queryVersionActionToCmdQueue()" :loading='queryVersionLoading'>
                <span title='从终端获取固件版本'>获取固件版本</span>
              </a-button>
            </a-space>
          </template>


          <template #bodyCell="{ column, record }">
            <template v-if="column.key == 'processStatus'">
              <a-tag v-if="record.upgradeState == 3" color="green">成功</a-tag>
              <a-tag v-else-if="record.upgradeState == 4" color="red">失败</a-tag>
              <a-tag v-else-if="record.upgradeState == 5" color="red">终止</a-tag>
              <a-progress v-else-if="record.upgradeState == 1" type="circle" :percent="0" :width="40" />
              <a-progress v-else-if="record.upgradeState == 2" type="circle" :percent="Math.round((record.currentPackage / record.totalPackage) * 100)" :width="40" />
              <a-tag v-else color="red">未知</a-tag>
            </template>

            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space v-permission="['PROPERTY_DEVICELIST_MGR_SLURRY_SOFTWARE_Upgrade_DEL_BUTTON']">
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>

    <DeviceSlurryscraperFirmwareUpgradeEdit v-if="showEdit" v-model:visible="showEdit" :data="current" :deviceRecord="data" @done="reload" />
  </div>
</template>

<script>
import { PlusOutlined } from '@ant-design/icons-vue';
import DeviceSlurryscraperFirmwareUpgradeEdit from './slurryscraper-firmware-upgrade-edit.vue'
import { message } from 'ant-design-vue';
import {DeviceSlurryScraperUpgradeApi} from "@/api/property/slurryscraper/DeviceSlurryScraperUpgradeApi";
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';

export default {
  name: 'DeviceSlurryscraperFirmwareUpgrade',
  components: {
    PlusOutlined,
    DeviceSlurryscraperFirmwareUpgradeEdit
  },
  props: {
    data: Object
  },
  async mounted() {
    this.loadDetailTimer = setInterval(this.reload, 60000);
  },
  beforeUnmount() {
    clearInterval(this.loadDetailTimer);
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '目标版本',
          dataIndex: 'firmwareVersion',
          customRender: function(row) {
            return "📈版本" + row.text;
          }
        },
        {
          title: '总包数',
          dataIndex: 'totalPackage'
        },
        {
          title: '状态',
          key : 'processStatus',
          dataIndex: 'upgradeState',
        },
        {
          title: '升级信息',
          dataIndex: 'msg'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center'
        }
      ],
      // 表格搜索条件
      where: {"recordId" : this.data.recordId},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      loadDetailTimer : null,

      queryVersionLoading : false,
      queryVersionTimer : undefined
    };
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/04/03 18:31
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/04/03 18:31
     */
    reset() {
      this.where = {"recordId" : this.data.recordId};
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2022/04/03 18:31
     */
    async remove(row) {
      const result = await DeviceSlurryScraperUpgradeApi.delete({ upgradeId: row.upgradeId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2022/04/03 18:31
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },


    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    clearGetVersionFromDeviceProcess(){
      this.queryVersionLoading = false;
      clearInterval(this.queryVersionTimer);
      this.queryVersionTimer = null;
    },
    checkGetVersionFromDeviceProcess() {
      let that = this;
      this.checkProcess(34, this.clearGetVersionFromDeviceProcess, function(){
        that.init();
      });
    },
    queryVersionActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 34
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.getVersionFromDevice();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    getVersionFromDevice () {
      this.loading = true;
      let updateData = {
        old: '',
        update: '',
      };
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'scraper',
        updateData: JSON.stringify(updateData),
        dictate : 34,
        sceneDictate : 34
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.queryVersionLoading = true;
          this.queryVersionTimer = setInterval(this.checkGetVersionFromDeviceProcess, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      return DeviceSlurryScraperUpgradeApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    }
  }
};
</script>
